import React, { useState, useEffect } from 'react';
import { Tabs, message } from 'antd';
import InterfaceInfo from './interfaceInfo';
import PublishHistory from '../../components/Detail/publishHistory';
import AuthorizeInfo from '../../components/Detail/authorizeInfo';
import Debug from '../../components/Detail/debug';
import InterfaceDoc from '../../components/Detail/interfaceDoc';
import services from '../../../../../services/api';

const MainSpareInterfaceDetail = (props) => {
  const [data, setData] = useState({});
  // 通过path区分主备接口 分流接口 true 为主备 false分流
  const interfaceType = props.match.path.includes('mainSpareInterface');
  const id = props.match.params.id;

  useEffect(() => {
    getInnerInterfaceDetail();
  }, []);

  const getInnerInterfaceDetail = async () => {
    const { code, msg, data } = await services.interfaceManage.detail(id);
    if (code) return message.error(msg);
    // 构造数据源接口的map
    const { thirdInterfaceList, returningMaps, tparams } = data;
    const interfaceMap = {};
    thirdInterfaceList.forEach((item) => (interfaceMap[item.id] = [item.name, item.supplierName]));
    data['interfaceMap'] = interfaceMap;
    // 构造返回值映射
    const tempObj = {};
    returningMaps &&
      returningMaps.forEach((item) => {
        const { innerPath } = item;
        if (!tempObj[innerPath]) {
          tempObj[innerPath] = {
            thirdInterfaceList: [item],
            ...item,
          };
        } else {
          tempObj[innerPath].thirdInterfaceList.push(item);
        }
      });
    data.returningMaps = Object.values(tempObj);
    // 构造常量tab
    const tempTabList =
      thirdInterfaceList &&
      thirdInterfaceList.map(({ name, id }) => ({
        name,
        tparams: tparams.filter((item) => item.interfaceId === id),
      }));
    data['tabList'] = tempTabList;
    setData(data);
  };

  const tabList = [
    {
      key: '0',
      title: '接口信息',
      component: InterfaceInfo,
    },
    {
      key: '1',
      title: '发布历史',
      component: PublishHistory,
    },
    {
      key: '2',
      title: '授权信息',
      component: AuthorizeInfo,
    },
    {
      key: '3',
      title: '接口调试',
      component: Debug,
    },
    {
      key: '4',
      title: '接口文档',
      component: InterfaceDoc,
    },
  ];

  return (
    <Tabs style={{ width: '100%' }} defaultActiveKey='0'>
      {tabList.map((item) => (
        <Tabs.TabPane tab={item.title} key={item.key} forceRender={true}>
          <item.component {...props} value={data} interfaceType={interfaceType} />
        </Tabs.TabPane>
      ))}
    </Tabs>
  );
};
export default MainSpareInterfaceDetail;
